package io.renren.modules.sq.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.utils.RandomUtils;
import io.renren.common.utils.ResponseData;
import io.renren.modules.sq.dto.SysAuthDto;
import io.renren.modules.sq.entity.SqSystemAuthorizationCodeEntity;
import io.renren.modules.sq.entity.SqSystemEditionEntity;
import io.renren.modules.sq.entity.SqSystemEntity;
import io.renren.modules.sq.service.SqSystemAuthorizationCodeService;
import io.renren.modules.sq.service.SqSystemEditionService;
import io.renren.modules.sq.service.SqSystemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Slf4j
@Api(tags = "系统版本")
@RestController
@RequestMapping("sys/sqsystemedition")
public class SqSystemEditionController {
    @Autowired
    private SqSystemService sqSystemService;
    @Autowired
    private SqSystemEditionService sqSystemEditionService;
    @Autowired
    private SqSystemAuthorizationCodeService sqSystemAuthorizationCodeService;
    /**
     * 列表
     */
    @ApiOperation("获取系统版本列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页pageIndex", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "limit", value = "每页数量pageSize", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "systemId", value = "系统id", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "systemEdition", value = "系统版本", paramType = "query", dataType = "String", required = false),
            @ApiImplicitParam(name = "systemDescription", value = "描述", paramType = "query", dataType = "String", required = false),
            // @ApiImplicitParam(name = "roleId", value = "允许生成授权码0：禁止1：允许", paramType = "query", dataType = "String", required = false),
    })
    public ResponseData<Page<SqSystemEditionEntity>> list(@RequestParam Map<String, Object> params){
        Page<SqSystemEditionEntity> page = sqSystemEditionService.getSysEditionList(params);
        for (SqSystemEditionEntity record : page.getRecords()) {
            record.setSystemName(sqSystemService.getById(record.getSystemId()).getSystemName());
        }
        return ResponseData.success(page);
    }


    /**
     * 信息
     */
    @ApiOperation("通过系统版本id获取信息")
    @GetMapping("/info/{id}")
    public ResponseData<SqSystemEditionEntity> info(@PathVariable("id") Long id){
        SqSystemEditionEntity sqSystemEdition = sqSystemEditionService.getById(id);
        return ResponseData.success(sqSystemEdition);
    }

    /**
     * 保存
     */
    @ApiOperation("新增系统版本（需要传系统id）")
    @PostMapping("/save")
    public ResponseData save(@RequestBody SqSystemEditionEntity sqSystemEdition){
        try {
            sqSystemEdition.setCreateTime(new Date());
            boolean flag = sqSystemEditionService.save(sqSystemEdition);
            return ResponseData.success(flag ? "创建成功" : "创建失败", flag);
        } catch (Exception e) {
            log.error("新增系统接口异常" + Arrays.toString(e.getStackTrace()));
            return ResponseData.error(-1, "系统名称, 系统版本不能重复");
        }
    }

    /**
     * 修改
     */
    @Transactional
    @ApiOperation("修改系统版本")
    @PostMapping("/update")
    public ResponseData update(@RequestBody SqSystemEditionEntity sqSystemEdition){
        try {
            boolean flag = sqSystemEditionService.updateById(sqSystemEdition);
            return ResponseData.success(flag ? "修改成功" : "修改失败", flag);
        } catch (Exception e) {
            log.error("修改系统版本接口异常" + Arrays.toString(e.getStackTrace()));
            return ResponseData.error(-1, "系统名称, 系统版本不能重复");
        }
    }

    /**
     * 删除
     */
    @Transactional
    @ApiOperation("删除系统版本（单个+多个）")
    @PostMapping("/delete")
    public ResponseData delete(@RequestBody List<Long> ids){
        boolean flag = sqSystemEditionService.removeByIds(ids);
        return ResponseData.success(flag ? "删除成功" : "删除失败", flag);
    }

    @Transactional
    @ApiOperation("为系统版本创建指定数量的授权码")
    @PostMapping("/createAuthCode")
    public ResponseData createAuthCode(@RequestBody SysAuthDto sysAuthDto){
        Integer num = sysAuthDto.getNum();
        if(num == null || num <= 0) {
            return ResponseData.error(-1, "数量要大于0");
        }
        StringBuilder errStr = new StringBuilder();
        for (Long id : sysAuthDto.getIds()) {
            SqSystemEditionEntity systemEdition = sqSystemEditionService.getById(id);
            SqSystemEntity systemEntity = sqSystemService.getById(systemEdition.getSystemId());
            if(systemEntity.getAllow() == 0) {
                errStr.append(systemEdition.getSystemId()).append("系统不允许生成授权码<br/>");
                continue;
            }
            Long newCreateCodeNum = 1L;
            SqSystemAuthorizationCodeEntity entity = sqSystemAuthorizationCodeService.getOne(new QueryWrapper<SqSystemAuthorizationCodeEntity>().select("max(create_code_num) as create_code_num").eq("user_id", sysAuthDto.getUserId()).eq("system_edition_id", id));
            if(entity != null) {
                newCreateCodeNum = entity.getCreateCodeNum() + 1;
            }
            List<SqSystemAuthorizationCodeEntity> list = new ArrayList<>();
            for(int i = 0; i < num; i++) {
                SqSystemAuthorizationCodeEntity codeEntity = new SqSystemAuthorizationCodeEntity();
                codeEntity.setRemarks(sysAuthDto.getRemarks()).setCreateCodeNum(newCreateCodeNum).setSystemCode(RandomUtils.randomUtil()).setSystemEditionId(id).setUsed(0).setUserId(sysAuthDto.getUserId()).setCreateTime(new Date()).setSystemEdition(systemEdition.getSystemEdition()).setSystemName(systemEntity.getSystemName());
                list.add(codeEntity);
            }
            sqSystemAuthorizationCodeService.saveBatch(list);
        }
        boolean flag = errStr.length() != 0;
        return ResponseData.success(flag ? "创建成功" : errStr.toString());
    }
}
